<template>
  <div class='container'>
    <el-dialog
      :title="form.id?'修改学科': '新增学科'"
      :visible="dialogVisible"
      width="30%"
      @close="close"
      @closed="closed"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="学科名称"
          prop="subjectName"
        >
          <el-input v-model="form.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="isFront"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="$emit('update:dialogVisible')">取 消</el-button>
        <el-button
          type="primary"
          @click="addData()"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入接口
import { add, detail, update } from '@/api/hmmm/subjects.js'
export default {
  props: {
    // 父组件传过来的变量
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  // 侦听器
  watch: {
    isFront () {
      this.display()
    }
  },
  data () {
    return {
      isFront: true,
      form: {
        subjectName: '',
        isFrontDisplay: null
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹层执行函数
    closed () {
      this.isFront = true
    },
    close () {
      this.form = {
        subjectName: '',
        isFrontDisplay: null,
        id: null,
        creator: '',
        addDate: null,
        twoLevelDirectory: '',
        tags: '',
        totals: null
      }
      this.$refs.form.resetFields()
      this.$emit('update:dialogVisible')
    },
    // 添加学科
    async addData () {
      try {
        this.$refs.form.validate()
        if (this.form.id) {
          await update(this.form)
          this.$parent.getList()
        } else {
          this.display()
          await add(this.form)
          this.$parent.sizeChange()
        }
        this.$message.success('操作成功')
        this.$emit('update:dialogVisible')
      } catch (error) {
        console.log(error)
      }
    },
    // 数据映射
    display () {
      const data = {
        true: 1,
        false: 0
      }
      this.form.isFrontDisplay = data[this.isFront]
    },
    // 修改
    async edUpDate (id) {
      if (id.isFrontDisplay === 1) {
        this.isFront = true
      } else {
        this.isFront = false
      }
      const { data } = await detail(id)
      this.form = data
      console.log(data)
    }
  }
}
</script>

<style scoped>
</style>
